package com.sdyeda.readiot.config;

import java.io.File;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import com.sdyeda.readiot.data.SetData;
import com.sdyeda.readiot.data.SetDataService;
import com.sdyeda.readiot.data.SetSave;
import com.sdyeda.readiot.data.SetSaveService;
import com.sdyeda.readiot.iotinfo.IotInfo;
import com.sdyeda.readiot.iotinfo.JdbcIotInfo;
import com.sdyeda.readiot.iotinfo.ReadingInfo;

@Component
public class Setting {
	
	// 常量 设置文件中
	public static final String SQL_GETIOTINFO = "sql-getiotinfo";
	//public static final String SQL_WRITEDATA = "sql-writedata";
	//public static final String SQL_READDATA = "sql-readdata";
	public static final String IOTTYPE = "iottype";
	
	public static final String SET_PASSWORD = "set-password";
	
	public static final String SCHEDULED_TYPE = "scheduled-type";
	public static final String SCHEDULED_DELAY = "scheduled-delay";
	public static final String SCHEDULED_CRON = "scheduled-cron";
		
	public static final String DATALOG = "datalog";
	public static final String RETRYTIMES = "retrytimes";
	public static final String INFODIR = "infodir";

	// 数据连接接口
	public static final String DATASOURCE_URL = "url";
	public static final String DATASOURCE_DRIVER = "driver-class-name";
	public static final String DATASOURCE_USERNAME = "username";
	public static final String DATASOURCE_PASSWORD = "password";

	// 系统日志文件名
	public static final String LOGGING_FILE_NAME = "logging.file.name";

	public static final String LOG_CONNECT_SUCCESS = "Connect open success!";
	public static final String LOG_CONNECT_FAILED = "Connect open failed!";
	public static final String LOG_CONNECT_CLOSE_SUCCESS = "Connect close success!";
	public static final String LOG_CONNECT_CLOSE_FAILED = "Connect close failed!";
	public static final String LOG_SEND_SUCCESS = "Send success= ";
	public static final String LOG_SEND_FAILED = "Send failed= ";
	public static final String LOG_SEND_SUCCESS_RECOEDS = "Success records= ";
	public static final String LOG_SEND_FAILED_RECOEDS = "Failed records= ";

	public static final String LOG_SEND_CLASS_NAME = "com.sdyeda.sendtosd.SendData";
	
	public static final String READINGINFO = "readinginfo";

	public static final String MAINWINDOW_CONTROLLER = "mainwindowcontroller";
	public static final String DETAILWINDOW_CONTROLLER = "detailwindowcontroller";


	public static final String ISREGISTERED = "isregistered";
	public static final String VALID_TIME = "valid_time";
	public static final String LicenseFile = "License.lic";
	public static final String LicenseStr = "License.str" ;
	
	// 数据连接接口
	public static Map<String, Object> setting = new HashMap<String, Object>();

	@Autowired
	private SettingConfig config;

	@Autowired
	private Environment envronment;  
	
	@Autowired
	private SetDataService setService;
	
	@Autowired
	private SetSaveService setSave;
	
	@PostConstruct
	void Init() {
		
		Map<String,SetData> sets = setService.getAllSetData();
		List<SetSave> setsaves = setSave.findAll();

		LoadSetting(sets,setsaves);

		ReadingInfo readinginfo =new ReadingInfo();
		List<IotInfo> list = JdbcIotInfo.getall();
		readinginfo.Init(list);
		LoadIotinfo(readinginfo);
		
		//自定义日志信息设置
		Set(DATALOG, config.isDatalog());
		Set(INFODIR,config.getInfodir());
		
			
		//日志文件名
		Set(LOGGING_FILE_NAME,envronment.getProperty(LOGGING_FILE_NAME));
		
		//建立日志目录
		Mkdir(config.getInfodir());
		
			
		//注册信息
		Set(LicenseStr,config.getLicense());
		if(License.getLicense()) {
			Set(ISREGISTERED,true);
		}
		else {
			Set(ISREGISTERED, false);
			Date now = new Date();
			Calendar calendar = new GregorianCalendar();
			calendar.setTime(now);
			calendar.add(Calendar.DATE, 1);// 1表示明天,-1表示昨天
			now = calendar.getTime();
			Set(VALID_TIME, now);
		}

	}
	
	//public void LoadIotinfo()
	//读取传感器信息
	static public void LoadIotinfo(ReadingInfo readinginfo) {
		//存储传感器读取信息
		Set(READINGINFO,readinginfo);
	}
	
	//载入参数
	static public void LoadSetting(Map<String,SetData> sets,List<SetSave> setsaves) {
		
		//系统JDBC参数
		Set(DATASOURCE_URL,sets.get(DATASOURCE_URL).getValue());
		Set(DATASOURCE_DRIVER,sets.get(DATASOURCE_DRIVER).getValue());
		Set(DATASOURCE_USERNAME,sets.get(DATASOURCE_USERNAME).getValue());
		Set(DATASOURCE_PASSWORD,sets.get(DATASOURCE_PASSWORD).getValue());
		//Sql语句s
		//System.out.println(sets.get(SQL_GETIOTINFO).getValue());
		
		Set(SQL_GETIOTINFO,sets.get(SQL_GETIOTINFO).getValue());
		//调零密码
		Set(SET_PASSWORD,sets.get(SET_PASSWORD).getValue());

		//定时任务参数
		Set(SCHEDULED_CRON,sets.get(SCHEDULED_CRON).getValue());
		Set(SCHEDULED_TYPE,sets.get(SCHEDULED_TYPE).getValue());
		try {
			Set(SCHEDULED_DELAY,Long.parseLong(sets.get(SCHEDULED_DELAY).getValue().trim()));
		}catch(Exception e) {
			Set(SCHEDULED_DELAY,3600000L);
		}
		
		//重试次数
		try {
			Set(RETRYTIMES, Integer.parseInt(sets.get(RETRYTIMES).getValue().trim()));
		} catch (Exception e) {
			Set(RETRYTIMES, 3);
		}
		
		//传感器写数据、读数据、类型
		Map<String,SetSave> iottypes = new HashMap<String, SetSave>();
		/*
		Map<String, String> writes = new HashMap<String, String>();
		Map<String, String> reads = new HashMap<String, String>();
		Map<String, String> types = new HashMap<String, String>();
		Map<String,String> jarpaths = new HashMap<String, String>();
		*/
		setsaves.forEach(item ->{
			iottypes.put(item.getIottype(), item);
			/*
			writes.put("sql"+item.getIottype(), item.getWritedata());
			reads.put("sql"+item.getIottype(), item.getReaddata());
			types.put(item.getIottype(), item.getTypename());
			*/
		});
		
		
		//Set(SQL_WRITEDATA,writes);
		///Set(SQL_READDATA,reads);
		Set(IOTTYPE,iottypes);
				
		
		//Set(SQL_WRITEDATA,config.getSqlWritedata());
		//Set(SQL_READDATA,config.getSqlReaddata());
		//Set(IOTTYPE,config.getIottype());


	}

	//类型map
	/*
	Map<String,String>getTypeMap(){
		Map<String,String> typemap = new HashMap<>();
		typemap.put("0","浸润线");
		typemap.put("1","库水位");
		typemap.put("4","测斜仪");
		typemap.put("5","雨量计");
		return typemap;
	}
	*/
	
	void Mkdir(String dir) {
		File fdir = new File(dir);
		if(!fdir.exists() && !fdir.isDirectory())
		{
			fdir.mkdirs();
		}
	}
	/*

	//刷新列表
	public static void RefreshIotTableList() {
		@SuppressWarnings("unchecked")
		TableView<IotData> tableview = (TableView<IotData>)ReadIotApplication.primaryStage.getScene().lookup("#iotList");
		if(tableview == null || tableview.getItems().size()==0) {
			return;
		}
		
		((ReadingInfo)Get(READINGINFO)).getList().forEach(item->{
			
			for(int i=0;i<tableview.getItems().size();i++) {
				if(tableview.getItems().get(i).getId()==item.getId()) {
					
					tableview.getItems().remove(i);
					tableview.getItems().add(i, item);
				}
			}			
			
		});;
		tableview.refresh();
		
		//tableview.setItems(FXCollections.observableArrayList(temp));
	}
	
	//不可执行。。。

	public static void RefreshIotTableList(IotData data) {
		@SuppressWarnings("unchecked")
		TableView<IotData> tableview = (TableView<IotData>)ReadIotApplication.primaryStage.getScene().lookup("#iotList");
		if(tableview == null ||tableview.getItems()==null) {
			return;
		}
		
		for(int i=0;i<tableview.getItems().size();i++) {
			if(tableview.getItems().get(i).getId()==data.getId()) {Setting
				
				tableview.getItems().remove(i);
				tableview.getItems().add(i, data);
			}
		}			
		
		tableview.refresh();
	}
	*/

	

	public static Object Get(String set) {
		return setting.get(set);
	}
	
	public static void Set(String set,Object value) {
		setting.put(set, value);
	}
}
